import React, { Component } from 'react'
import {connect} from "react-redux"
import {bindActionCreators} from "redux"
import * as action from "../action/index.js"
 class Shopcar extends Component {
    add(id){ // 购物车++
        this.props.Add(id)
    }
    del(id){ // 购物车--
      this.props.Del(id)
    }
    checkItem(id) { // 反选和每一项得选中事件
      this.props.checkitem(id)
    }
    checkAll(){ // 全选
        this.props.checkall()
    }
  render() {
    let checkitem = this.props.shoparr.filter((item,index)=>{ // 把当前选中的每一项放到checkitem这个数组里
      return item.flag
    })
    let addNum = checkitem.reduce((a,b)=>{ // 求和
      return a + b.price * b.number
    },0)
    return (
      <div>
          {
              this.props.shoparr&& this.props.shoparr.length?this.props.shoparr.map((item,index)=>{
                  return <div key={index}>
                      <input type="checkbox" checked={item.flag || ""} onChange={this.checkItem.bind(this,item.id)} />
                      <h4>商品名:{item.title}</h4>
                      <img src={item.img} alt="" />
                    <button onClick={this.del.bind(this,item.id)} >--</button>
                    <span>个数：{item.number}</span>
                    <button onClick={this.add.bind(this,item.id)}>++</button>
                    <span>价格：{item.price}</span>

                    
                  </div>
              }):"购物车空空"
          }
          <div>
            全选：<input type="checkbox" checked={this.props.checkAll} onChange={this.checkAll.bind(this)}/>
            <span>总和：{addNum}</span>
          </div>
      </div>
    )
  }
}
let mapStateToProps = (state)=>{
    return {
        ...state.shopReducer
    }
}
let mapDispatchToprops = (dispatch)=>bindActionCreators(action,dispatch)
export default connect(mapStateToProps,mapDispatchToprops)(Shopcar)